const app = getApp();

Page({
  data: {
    id: null,
    article: null,
    articleData: null,
    loading: true,
    error: null,
    isLoggedIn: false,
    userInfo: null,
    showToast: false,
    toastTitle: '',
    toastDuration: 2000,
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: 0,
    windowWidth: 0,
    isDragging: false,
    showFullGif: false,
    commentText: '',
    replyTo: null,
    // 评论相关
    commentText: '',
    replyTo: null,
    // 阅读计时相关
    readingTimer: null,
    readingStartTime: null,
    todayReadCount: 0,
    expandedComments: {}, // 记录展开状态的评论
    hasShared: false, // 添加分享状态
    showTooltip: false
  },

  onLoad(options) {
    const { id } = options;
    this.setData({ id });

    // 检查登录状态
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');

    if (!token || !userInfo) {
      this.setData({
        loading: false,
        error: '请先登录',
        isLoggedIn: false
      });
      return;
    }

    // 获取窗口信息
    try {
      const systemInfo = wx.getSystemInfoSync();
      this.setData({
        statusBarHeight: systemInfo.statusBarHeight,
        buttonTop: systemInfo.windowHeight - 180,
        buttonLeft: systemInfo.windowWidth - 160,
        windowHeight: systemInfo.windowHeight,
        windowWidth: systemInfo.windowWidth
      });
    } catch (e) {
      console.error('获取窗口信息失败：', e);
    }

    this.setData({
      isLoggedIn: true,
      userInfo: userInfo
    });

    // 获取文章详情
    this.fetchArticleComments();
    this.fetchArticleDetail();
    // 从缓存获取今日阅读次数
    const today = new Date().toDateString();
    const readRecord = wx.getStorageSync('readRecord') || {};

    if (readRecord.date === today) {
      this.setData({
        todayReadCount: readRecord.count || 0
      });
    } else {
      // 新的一天，重置阅读次数
      wx.setStorageSync('readRecord', {
        date: today,
        count: 0
      });
      this.setData({
        todayReadCount: 0
      });
    }
  },

  onShow() {
    // 开始计时
    if (this.data.todayReadCount < 3) {
      this.startReadingTimer();
    }
  },

  onHide() {
    // 清除计时器
    this.clearReadingTimer();
  },

  onUnload() {
    // 清除计时器
    this.clearReadingTimer();
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 开始阅读计时
  startReadingTimer() {
    if (this.data.todayReadCount >= 3) return;

    this.setData({
      readingStartTime: Date.now(),
      readingTimer: setTimeout(() => {
        this.addReadingPoints();
      }, 30000) // 30秒
    });
  },

  // 清除阅读计时器
  clearReadingTimer() {
    if (this.data.readingTimer) {
      clearTimeout(this.data.readingTimer);
      this.setData({
        readingTimer: null,
        readingStartTime: null
      });
    }
  },

  // 添加阅读积分
  addReadingPoints() {
    // 检查是否已达到今日上限
    if (this.data.todayReadCount >= 3) {
      return;
    }

    // 检查实际阅读时间是否达到30秒
    const readingTime = Date.now() - this.data.readingStartTime;
    if (readingTime < 30000) {
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) {
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/points/add',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        points: 3,
        source: '阅读文章奖励'
      },
      success: (res) => {
        if (res.statusCode === 401) {
          this.handleUnauthorized();
          return;
        }
        if (res.data.code === 200) {
          // 更新今日阅读次数
          const newCount = this.data.todayReadCount + 1;
          this.setData({
            todayReadCount: newCount
          });

          // 更新缓存中的阅读记录
          const today = new Date().toDateString();
          wx.setStorageSync('readRecord', {
            date: today,
            count: newCount
          });

          // 显示积分奖励提示
          wx.showToast({
            title: '获得3积分',
            icon: 'none',
            duration: 2000
          });

        }
      }
    });
  },

  onHide() {
    // 清除计时器
    this.clearReadingTimer();
  },

  onUnload() {
    // 清除计时器
    this.clearReadingTimer();
  },

  // 获取文章所有图片URL
  getArticleImageUrls(data) {
    const urls = [];
    const traverse = (node) => {
      if (node.tag === 'image' && node.attr && node.attr.src) {
        urls.push(node.attr.src);
      }
      if (node.children && node.children.length) {
        node.children.forEach(traverse);
      }
    };
    traverse(data);
    return urls;
  },

  // 获取文章详情
  async fetchArticleDetail() {
    if (!this.data.isLoggedIn) {
      this.setData({
        error: '请先登录',
        loading: false
      });
      return;
    }

    const token = wx.getStorageSync('token');
    const { id } = this.data;

    try {
      this.setData({ loading: true, error: '' });

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `https://www.haoyuming.online/api/user/article/${id}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            if (res.statusCode === 401) {
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
              this.setData({
                isLoggedIn: false,
                userInfo: null
              });
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none'
              });
              wx.navigateTo({
                url: '/pages/login/login'
              });
              reject(new Error('未授权'));
              return;
            }
            resolve(res.data);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });

      console.log('API返回数据:', res);

      if (res.code === 200 && res.data) {
        // 处理文章数据
        const article = {
          ...res.data,
          createTime: this.formatDate(res.data.createTime),
          tags: res.data.tags ? res.data.tags.split(',').map(tag => ({
            name: tag.trim()
          })) : []
        };

        // 使用 towxml 解析 Markdown 内容
        let content = res.data.content || '';

        // 先处理图片，确保它们能正确显示
        content = content.replace(/!\[(.*?)\]\((.*?)\)/g, (match, alt, url) => {
          // 返回特殊格式的图片标记，稍后会被towxml处理
          return `<img src="${url}" alt="${alt}" style="max-width:100%;display:block;margin:20rpx auto;"/>`;
        });

        // 使用 towxml 处理内容
        article.content = app.towxml(content, 'markdown', {
          theme: 'light',
          events: {
            tap: (e) => {
              const dataset = e.currentTarget.dataset;
              // 处理图片点击预览
              if (dataset.data && dataset.data.attr && dataset.data.attr.src) {
                wx.previewImage({
                  current: dataset.data.attr.src,
                  urls: [dataset.data.attr.src]
                });
              }
              // 处理代码复制
              if (dataset.data && dataset.data.attr && dataset.data.attr.class === 'copy-btn') {
                const codeText = dataset.data.parent.children[0].text;
                wx.setClipboardData({
                  data: codeText,
                  success: () => {
                    wx.showToast({
                      title: '代码已复制',
                      icon: 'success',
                      duration: 2000
                    });
                  }
                });
              }
            }
          }
        });

        // 遍历文章内容，为代码块添加复制按钮
        const addCopyButtons = (node) => {
          if (node.tag === 'pre') {
            // 确保代码块有子节点
            if (node.children && node.children.length > 0) {
              // 添加复制按钮
              node.children.push({
                tag: 'button',
                attr: {
                  class: 'copy-btn',
                  style: 'position:absolute;top:16rpx;right:16rpx;'
                },
                children: [{
                  text: '复制',
                  type: 'text'
                }]
              });
            }
          }
          // 递归处理子节点
          if (node.children) {
            node.children.forEach(child => {
              if (typeof child === 'object') {
                addCopyButtons(child);
              }
            });
          }
        };

        // 处理文章内容中的所有节点
        if (article.content.child) {
          article.content.child.forEach(node => addCopyButtons(node));
        }

        console.log('处理后的文章数据:', article);

        this.setData({
          article,
          loading: false
        });

        // 设置页面标题
        wx.setNavigationBarTitle({
          title: article.title || '文章详情'
        });

        // 获取评论列表
        this.fetchArticleComments();
      } else {
        this.setData({
          error: res.message || '获取文章失败',
          loading: false
        });
      }
    } catch (error) {
      console.error('获取文章详情失败:', error);
      this.setData({
        error: '获取文章失败，请重试',
        loading: false
      });
    }
  },

  // 格式化日期
  formatDate(dateString) {
    if (!dateString) return '';
    // 将日期字符串转换为 iOS 支持的格式
    const formattedString = dateString.replace(' ', 'T');
    const date = new Date(formattedString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 分享
  onShareAppMessage(options) {
    const article = this.data.article;
    if (!article) return;

    // 检查登录状态
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 检查是否从任务页面跳转来的
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    const isFromTask = prevPage && prevPage.route === 'pages/profile/profile';

    // 如果是从任务页面来的，才检查分享次数限制
    if (isFromTask) {
      // 检查分享次数
      const today = new Date().toDateString();
      const shareRecord = wx.getStorageSync('shareRecord') || {};
      const currentCount = shareRecord.date === today ? (shareRecord.count || 0) : 0;

      if (currentCount >= 3) {
        wx.showToast({
          title: '今日获得积分次数已达上限',
          icon: 'none'
        });
        // 仍然允许分享，但不给积分
        return {
          title: article.title,
          path: `/pages/article-detail/article-detail?id=${article.id}`,
          imageUrl: article.coverImage || '',
        };
      }

      // 更新分享记录并添加积分
      wx.setStorageSync('shareRecord', {
        date: today,
        count: currentCount + 1
      });

      // 添加积分
      const token = wx.getStorageSync('token');
      wx.request({
        url: 'https://www.haoyuming.online/api/user/points/add',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          points: 3,
          source: '分享文章奖励'
        },
        success: (res) => {
          if (res.data.code === 200) {
            wx.showToast({
              title: '分享成功，获得3积分',
              icon: 'success'
            });
          }
        }
      });
    }

    // 设置分享状态
    this.setData({
      hasShared: true
    });

    return {
      title: article.title,
      path: `/pages/article-detail/article-detail?id=${article.id}`,
      imageUrl: article.coverImage || '',
      success: (res) => {
        console.log('分享成功');
      },
      fail: (res) => {
        console.log('分享失败');
        // 分享失败时重置状态
        this.setData({
          hasShared: false
        });
      }
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const { article } = this.data;
    return {
      title: article ? article.title : '精彩文章',
      query: `id=${this.data.id}`,
      imageUrl: article ? article.cover : ''
    };
  },

  // 显示自定义提示
  showCustomToast(title, duration = 2500) {
    this.setData({
      showToast: true,
      toastTitle: title,
      toastDuration: duration
    });
  },

  // 提示隐藏回调
  onToastHide() {
    this.setData({
      showToast: false,
      toastTitle: ''
    });
  },

  // 点赞
  onLikeTap() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: `https://www.haoyuming.online/api/user/article/${this.data.id}/like`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 401) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          this.setData({
            isLoggedIn: false,
            userInfo: null
          });
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          return;
        }

        if (res.data.code === 200) {
          // 更新点赞状态和数量
          this.setData({
            'article.isLiked': !this.data.article.isLiked,
            'article.likes': this.data.article.isLiked ?
              this.data.article.likes - 1 :
              this.data.article.likes + 1
          });

          wx.showToast({
            title: this.data.article.isLiked ? '点赞成功' : '取消点赞',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('点赞失败：', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 评论输入
  onCommentInput(e) {
    const value = e.detail.value;
    this.setData({
      commentText: value,
    });
  },

  // 提交评论
  onCommentSubmit() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const content = this.data.commentText.trim();
    if (!content) {
      return; // 如果内容为空，直接返回
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: 'https://www.haoyuming.online/api/user/comment',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        articleId: this.data.id,
        content: content,
        parentId: this.data.replyTo ? this.data.replyTo.id : 0
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '评论成功',
            icon: 'success'
          });
          // 清空输入框和回复目标
          this.setData({
            commentText: '',
            replyTo: null
          });
          // 重新获取评论列表
          this.fetchArticleComments();
        } else {
          wx.showToast({
            title: res.data.msg || '评论失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 取消回复
  cancelReply() {
    this.setData({
      replyTo: null,
      commentText: ''
    });
  },

  // 获取文章评论
  fetchArticleComments() {
    const token = wx.getStorageSync('token');
    wx.request({
      url: `https://www.haoyuming.online/api/user/comment/article/${this.data.id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          const comments = res.data.data || [];
          // 处理评论时间和数据
          comments.forEach(comment => {
            comment.createTime = this.formatDate(comment.createTime);
            if (comment.children && comment.children.length) {
              comment.children.forEach(reply => {
                reply.createTime = this.formatDate(reply.createTime);
              });
            }
          });

          this.setData({
            'article.comments': comments  // 直接更新 article.comments
          });
        } else {
          console.error('获取评论失败：', res.data.msg);
        }
      },
      fail: (err) => {
        console.error('获取评论失败：', err);
      }
    });
  },

  // AI分析处理
  handleAIAnalyze() {
    if (this.data.isAnalyzing) return;

    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isAnalyzing: true,
      showAnalysis: true,
      keywordsList: [],
      analysisResult: {
        summary: '',
        keywords: '',
        mainPoints: ''
      }
    });

    wx.request({
      url: `https://www.haoyuming.online/api/user/article/${this.data.id}/summary`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 模拟加载时间，增加用户体验
          setTimeout(() => {
            // 处理关键词，确保格式正确
            const keywords = res.data.data.keywords || '';
            const keywordsList = keywords
              .split(',')
              .map(item => item.trim())
              .filter(item => item);

            this.setData({
              isAnalyzing: false,
              keywordsList,
              analysisResult: {
                summary: res.data.data.summary || '',
                keywords: keywords,
                mainPoints: res.data.data.mainPoints || ''
              }
            });
          }, 1500);
        } else {
          this.setData({
            isAnalyzing: false
          });
          wx.showToast({
            title: res.data.msg || '分析失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('AI分析失败：', err);
        this.setData({
          isAnalyzing: false
        });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 关闭分析结果
  closeAnalysis() {
    if (this.data.isAnalyzing) return;
    this.setData({
      showAnalysis: false
    });
  },

  // 点击回复按钮
  onReplyTap(e) {
    if (!this.data.isLoggedIn) {
      this.showCustomToast('请先登录', 2500);
      return;
    }

    const comment = e.currentTarget.dataset.comment;
    const parent = e.currentTarget.dataset.parent;

    // 如果已经是二级评论，则回复其父评论
    if (parent) {
      this.setData({
        replyTo: {
          id: parent.id,
          userName: comment.userName,
          parentId: parent.id
        }
      });
      return;
    }

    // 一级评论直接回复
    this.setData({
      replyTo: {
        id: comment.id,
        userName: comment.userName,
        parentId: comment.id
      }
    });
  },

  // 取消回复
  cancelReply() {
    this.setData({
      replyTo: null,
      commentText: ''
    });
  },

  // 长按评论
  onCommentLongPress(e) {
    const comment = e.currentTarget.dataset.comment;

    wx.showActionSheet({
      itemList: ['删除'],
      itemColor: '#ff4444',
      success: (res) => {
        if (res.tapIndex === 0) {
          this.deleteComment(comment.id);
        }
      }
    });
  },

  // 删除评论
  deleteComment(commentId) {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          const token = wx.getStorageSync('token');
          wx.request({
            url: `https://www.haoyuming.online/api/user/comment/${commentId}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${token}`
            },
            success: (res) => {
              if (res.data.code === 200) {
                this.showCustomToast('删除成功');
                // 重新获取评论列表
                this.fetchArticleComments();
              } else {
                this.showCustomToast(res.data.msg || '删除失败');
              }
            },
            fail: () => {
              this.showCustomToast('网络错误，请稍后重试');
            }
          });
        }
      }
    });
  },

  // 按钮触摸开始
  onAIButtonStart(e) {
    this.startX = e.touches[0].clientX;
    this.startY = e.touches[0].clientY;
    this.buttonTop = this.data.buttonTop;
    this.buttonLeft = this.data.buttonLeft;
    this.setData({
      isDragging: true,
      isExpanded: true,
      showTooltip: true
    });
  },

  // 按钮移动
  onAIButtonMove(e) {
    if (this.data.isDragging) {
      const touch = e.touches[0];
      const deltaX = touch.clientX - this.startX;
      const deltaY = touch.clientY - this.startY;

      let newLeft = this.buttonLeft + deltaX;
      let newTop = this.buttonTop + deltaY;

      // 获取屏幕尺寸
      try {
        const windowInfo = wx.getWindowInfo();
        const maxLeft = windowInfo.windowWidth - 40;  // 按钮宽度
        const maxTop = windowInfo.windowHeight - 100;

        // 限制按钮在屏幕内
        newLeft = Math.max(0, Math.min(maxLeft, newLeft));
        newTop = Math.max(10, Math.min(maxTop, newTop));

        this.setData({
          buttonLeft: newLeft,
          buttonTop: newTop
        });
      } catch (e) {
        console.error('获取窗口信息失败：', e);
      }
    }
  },

  // 按钮触摸结束
  onAIButtonEnd() {
    try {
      const windowInfo = wx.getWindowInfo();
      const screenWidth = windowInfo.windowWidth;
      let newLeft = this.data.buttonLeft;

      // 判断按钮更靠近哪边
      if (newLeft > screenWidth / 2) {
        // 靠右
        newLeft = screenWidth - 40;  // 按钮宽度
      } else {
        // 靠左
        newLeft = 0;
      }

      this.setData({
        isDragging: false,
        isExpanded: false,
        buttonLeft: newLeft,
        showTooltip: false
      });

      // 延迟收起文字
      setTimeout(() => {
        if (!this.data.isDragging) {
          this.setData({ isExpanded: false });
        }
      }, 3000);
    } catch (e) {
      console.error('获取窗口信息失败：', e);
    }
  },

  // 复制分析结果
  copyAnalysisResult() {
    const { summary, keywords, mainPoints } = this.data.analysisResult;
    const copyText = `【文章摘要】\n${summary}\n\n【关键词】\n${keywords}\n\n【主要观点】\n${mainPoints}`;

    wx.setClipboardData({
      data: copyText,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/profile/profile'
    });
  },

  // 复制代码
  copyCode(e) {
    const code = e.currentTarget.dataset.code;
    if (!code) {
      wx.showToast({
        title: '复制失败',
        icon: 'none'
      });
      return;
    }

    wx.setClipboardData({
      data: code,
      success: () => {
        wx.showToast({
          title: '代码已复制',
          icon: 'success',
          duration: 2000
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 图片加载失败处理
  imageError(e) {
    console.log('图片加载失败', e);
    const defaultImage = '/assets/images/image-placeholder.png';

    const node = e.target.dataset._el;
    if (node) {
      // 打印更多信息以便调试
      console.log('图片节点信息：', node);
      console.log('原始图片路径：', node.attr.src);

      node.attr.src = defaultImage;
      this.setData({
        articleData: this.data.articleData
      });
    }
  },

  // 图片预览功能
  previewImage(e) {
    console.log('预览图片', e);
    const node = e.target.dataset._el;
    if (!node || !node.attr || !node.attr.src) {
      console.log('无效的图片节点');
      return;
    }

    const currentUrl = node.attr.src;
    console.log('当前图片URL：', currentUrl);

    // 预览图片
    wx.previewImage({
      current: currentUrl,
      urls: [currentUrl],
      fail: (err) => {
        console.error('预览图片失败：', err);
      }
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 处理文章内容
  async processArticleContent(content) {
    try {
      console.log('原始内容:', content);

      // 处理图片链接
      const imgReg = /!\[(.*?)\]\((.*?)\)/g;
      content = content.replace(imgReg, (match, alt, url) => {
        if (!url.startsWith('http')) {
          url = 'https://tryokey.oss-cn-beijing.aliyuncs.com/' + url;
        }
        return `![${alt}](${url})`;
      });

      console.log('处理后的内容:', content);

      // 使用 app.towxml 方法
      const app = getApp();
      const articleData = app.towxml(content, 'markdown', {
        theme: 'light',
        events: {
          tap: (e) => {
            // 处理图片点击，显示预览
            if (e.currentTarget.dataset.data &&
              e.currentTarget.dataset.data.attr &&
              e.currentTarget.dataset.data.attr.src) {
              wx.previewImage({
                current: e.currentTarget.dataset.data.attr.src,
                urls: [e.currentTarget.dataset.data.attr.src]
              });
            }
          },
          // 处理代码复制
          imgtap: (e) => {
            const node = e.currentTarget.dataset.data;
            if (node.attr && node.attr.src) {
              wx.previewImage({
                current: node.attr.src,
                urls: [node.attr.src]
              });
            }
          }
        }
      });

      console.log('解析后的数据:', articleData);
      return articleData;
    } catch (error) {
      console.error('Markdown 解析错误:', error);
      const app = getApp();
      return app.towxml('内容解析失败', 'markdown', {
        theme: 'light'
      });
    }
  },

  // 处理点击事件
  onTap(e) {
    // 处理代码复制
    if (e.currentTarget.dataset.data && e.currentTarget.dataset.data.attr && e.currentTarget.dataset.data.attr.class === 'h2w__code') {
      const code = e.currentTarget.dataset.data.text;
      wx.setClipboardData({
        data: code,
        success: () => {
          wx.showToast({
            title: '代码已复制',
            icon: 'success'
          });
        }
      });
    }
  },

  // 处理图片点击
  onImageTap(e) {
    const node = e.currentTarget.dataset.data;
    if (node && node.attr && node.attr.src) {
      const src = node.attr.src;
      // 收集文章中所有图片URL
      const urls = [];
      const collectImageUrls = (nodes) => {
        if (!nodes) return;
        nodes.forEach(node => {
          if (node.tag === 'image' && node.attr && node.attr.src) {
            urls.push(node.attr.src);
          }
          if (node.children && node.children.length) {
            collectImageUrls(node.children);
          }
        });
      };

      if (this.data.articleData && this.data.articleData.child) {
        collectImageUrls(this.data.articleData.child);
      }

      wx.previewImage({
        current: src,
        urls: urls.length ? urls : [src]
      });
    }
  },

  // 添加展开收起方法
  toggleReplies(e) {
    const commentId = e.currentTarget.dataset.commentId;
    console.log('Toggle replies for comment:', commentId);
    console.log('Current state:', this.data.expandedComments[commentId]);

    const newExpandedState = !this.data.expandedComments[commentId];
    console.log('New state:', newExpandedState);

    this.setData({
      [`expandedComments.${commentId}`]: newExpandedState
    }, () => {
      console.log('Updated state:', this.data.expandedComments);
    });
  },

  // GIF拖动相关方法
  onGifStart(e) {
    const touch = e.touches[0];
    this.startX = touch.clientX;
    this.startY = touch.clientY;
    this.lastLeft = this.data.buttonLeft;
    this.lastTop = this.data.buttonTop;
    this.setData({ isDragging: true });
  },

  onGifMove(e) {
    if (!this.data.isDragging) return;

    const touch = e.touches[0];
    const deltaX = touch.clientX - this.startX;
    const deltaY = touch.clientY - this.startY;

    let newLeft = this.lastLeft + deltaX;
    let newTop = this.lastTop + deltaY;

    // 边界检查（使用缓存的窗口尺寸）
    const maxLeft = this.data.windowWidth - 80;
    const maxTop = this.data.windowHeight - 80;

    if (newLeft < 0) newLeft = 0;
    if (newTop < 0) newTop = 0;
    if (newLeft > maxLeft) newLeft = maxLeft;
    if (newTop > maxTop) newTop = maxTop;

    // 使用节流更新位置
    if (!this.moveTimer) {
      this.moveTimer = setTimeout(() => {
        this.setData({
          buttonLeft: newLeft,
          buttonTop: newTop
        });
        this.moveTimer = null;
      }, 16); // 约60fps的更新频率
    }
  },

  onGifEnd() {
    if (this.moveTimer) {
      clearTimeout(this.moveTimer);
      this.moveTimer = null;
    }
    this.setData({ isDragging: false });
  },

  // 显示全屏GIF
  showFullScreenGif() {
    this.setData({ showFullGif: true });
    setTimeout(() => {
      this.setData({ showFullGif: false });
    }, 3000);
  },

  // 隐藏全屏GIF
  hideFullScreenGif() {
    this.setData({ showFullGif: false });
  }
});